<template>
  <div class="main-container">
    <div class="header">
      <el-button @click="openPost()" class="post-button">发帖</el-button>
    </div>
    <div class="post-list-container">
      <div class="post-item" v-for="(post, index) in currentPagePosts" :key="index">
        <el-avatar :src="post.postAvater" class="post-avatar"></el-avatar>
        <div  class="post-content"   @click="postPage(post.postId)">
          <div v-html="post.title" class="post-title" ></div>
          <div v-html="post.postContent" ></div>
        </div>
        <div class="post-stats">
          <span>评论数：{{ post.commentList.length }}</span>
          <span>点赞量: {{ post.support }}</span>
        </div>
      </div>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 30]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="allPosts.length"
      >
      </el-pagination>
    </div>

    <el-dialog
      v-model="dialogVisible"
      title="Tips"
      width="800"
      :before-close="handleClose"
      class="post-dialog"
    >
      <el-input v-model="newPostTitle" placeholder="标题" class="post-input"></el-input>
      <template #footer>
        <div class="editor-container">
          <Toolbar
            style="border-bottom: 1px solid #ccc"
            :editor="editorRef"
            :defaultConfig="toolbarConfig"
            :mode="mode"
          />
          <Editor
            style="height: 500px; overflow-y: hidden"
            v-model="valueHtml"
            :defaultConfig="editorConfig"
            :mode="mode"
            @onCreated="handleCreated"
            class="post-editor"
          />
          <div class="button-container">
            <el-button @click="toPost()" class="post-submit-button">发帖</el-button>
            <el-button @click="toPostcancel()" class="post-cancel-button">取消</el-button>
          </div>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { useRoute, useRouter } from "vue-router";
import axios from "axios";
import { onBeforeUnmount, ref, shallowRef, onMounted } from "vue";
import { config, userConfig } from "@/config/config";
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";

let router = useRoute()
let route=useRouter()
const allPosts = ref([])
const currentPagePosts = ref([])
const dialogVisible = ref(false)
const newPostTitle = ref('')
const currentPage = ref(1)
const pageSize = ref(10)

const editorRef = shallowRef();
let QiniuToken=ref()

// 内容 HTML
const valueHtml = ref("<p>hello</p>");
const toolbarConfig = {};
const editorConfig = {
   placeholder: "请输入内容...",
   MENU_CONF: {
    
   }
   
  }
  editorConfig.MENU_CONF['uploadImage'] = {
    async customUpload(file, insertFn) {                   // JS 语法
    // file 即选中的文件
    // 自己实现上传，并得到图片 url alt href
    // 最后插入图片
   const finalurl= await handleFileChange(file)
   console.log("response:"+finalurl)
    insertFn(finalurl, null, finalurl)
  }
  }
onMounted(() => {
  setTimeout(() => {
    valueHtml.value = "<p>模拟 Ajax 异步设置内容</p>";
  }, 1500);

  getPostList()
})

onBeforeUnmount(() => {
  const editor = editorRef.value;
  if (editor == null) return;
  editor.destroy();
});

function postPage(postId) {
  route.push({
    name:"PostPage",
    query:{
      post:postId
    }
  })
}

const handleCreated = (editor) => {
  editorRef.value = editor; // 记录 editor 实例，重要！
};

const getPostList = () => {
  console.log(router.query.section)
  axios.get("api/Section/getPostList/" + router.query.section, userConfig).then(function (response) {
    allPosts.value = response.data.data
    console.log(allPosts.value)
    updateCurrentPagePosts()
  })
}

const updateCurrentPagePosts = () => {
  const startIndex = (currentPage.value - 1) * pageSize.value
  const endIndex = startIndex + pageSize.value
  currentPagePosts.value = allPosts.value.slice(startIndex, endIndex)
}

const handleSizeChange = (newSize) => {
  pageSize.value = newSize
  updateCurrentPagePosts()
}

const handleCurrentChange = (newPage) => {
  currentPage.value = newPage
  updateCurrentPagePosts()
}

const toPostcancel = () => {
  dialogVisible.value = false;
  valueHtml.value = "<p></p>";
};

function toPost() {
  console.log(valueHtml.value);
  dialogVisible.value = false;
  console.log();
  axios.post(
    "api/Section/addPost",
    {
      postId: "",
      title: newPostTitle.value,
      postMaster: localStorage.getItem("userId"),
      time: "",
      support: "0",
      comments: "0",
      forward: "0",
      sectionId: router.query.section,
      isBan: "0",
      postContent: valueHtml.value,
      beSupport: "",
      commentList: [],
      postAvater: "",
      parentPostId: '',
    },
    config
  ).then(function(response){
    if(response.status==200){
      getPostList()
    }
  });
}
const openPost=()=>{
  if(localStorage.getItem("userId")==null){
    alert("请登录")
  }else{
    dialogVisible.value = true
  }
}

const handleFileChange = async (Image) => {
    const file = Image
    console.log("选择文件已触发")
    if (file) {
      console.log("已找到文件")
      const qiniuKey = await uploadAvatarToQiniu(file);
      if (qiniuKey) {
        console.log("开始上传")
        const domain = 'http://svftekle7.hn-bkt.clouddn.com'; // 替换为你的七牛云存储空间域名
        const avatarUrl = `${qiniuKey}`;
        const finalUrl = domain+"/"+avatarUrl;
        return finalUrl
        //await sendAvatarUrlToBackend(avatarUrl);
      }
    }
  };

  // 从后端获取上传凭证的函数，这里假设你有一个后端接口可以返回 token
const getUploadToken = async () => {
  const userDto={
    id:''
  }
  try {
    const response = await axios.post('api/user/getQiniuToken',userDto,config)
    console.log(response)
    return response.data.data
    
  } catch (error) {
    console.error('获取上传凭证失败:', error);
    return null;
  }
};

// 上传头像到七牛云的函数
const uploadAvatarToQiniu = async (file) => {
  const token = await getUploadToken();
  QiniuToken.value=token;
  if (!token) {
    console.log("没有token",token)
    return;
  }

  const formData = new FormData();
  formData.append('token', token);
  formData.append('file', file);

  try {
    const response = await axios.post('https://up-z2.qiniup.com', formData, {
      headers: {
        'Content-Type': 'multipart/form-data',
      },
    });
    console.log('上传到七牛云成功:', response.data);
    //const finalUrl = domain+"/"+url;
    return response.data.key;
  } catch (error) {
    console.error('上传到七牛云失败:', error);
    return null;
  }
};

</script>

<style scoped>
.main-container {
  padding: 20px;
  background-color: #f0f5ff;
  min-height: 100vh;
}

.header {
  margin-bottom: 20px;
}

.post-button {
  background-color: #FFA07A;
  color: white;
  border: none;
  border-radius: 5px;
  padding: 10px 20px;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

.post-button:hover {
  background-color: #FF7F50;
}

.post-list-container {
  background-color: white;
  border-radius: 10px;
  padding: 20px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.post-item {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
  padding-bottom: 15px;
  border-bottom: 1px solid #eee;
}

.post-avatar {
  margin-right: 15px;
}

.post-content {
  flex: 1;
}

.post-title {
  color: #6A5ACD;
  font-size: 25px;
}

.post-dialog {
  border-radius: 10px;
  overflow: hidden;
}

.post-input {
  margin-bottom: 10px;
}

.editor-container {
  border: 1px solid #ccc;
  border-radius: 5px;
  overflow: hidden;
}

.post-editor {
  padding: 10px;
}

.button-container {
  display: flex;
  justify-content: flex-end;
  padding: 10px;
}

.post-submit-button {
  background-color: #32CD32;
  color: white;
  border: none;
  border-radius: 5px;
  padding: 10px 20px;
  cursor: pointer;
  transition: background-color 0.3s ease;
  margin-right: 10px;
}

.post-submit-button:hover {
  background-color: #228B22;
}

.post-cancel-button {
  background-color: #DC143C;
  color: white;
  border: none;
  border-radius: 5px;
  padding: 10px 20px;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

.post-cancel-button:hover {
  background-color: #B22222;
}

.post-stats {
  display: flex;
  justify-content: space-between;
  color: #78909c;
  font-size: 14px;
}
</style>    